package com.ruoyi.result.papers.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.result.Result;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.result.papers.domain.ResultPapers;
import com.ruoyi.result.papers.domain.dto.ResultPapersDTO;
import com.ruoyi.result.papers.domain.vo.ResultPapersVO;
import com.ruoyi.result.papers.mapper.ResultPapersMapper;
import com.ruoyi.result.papers.service.IResultPapersService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.team.trash.domain.AchievementTrash;
import com.ruoyi.team.trash.mapper.AchievementTrashMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 论文Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-13
 */
@Service
@Slf4j
public class ResultPapersServiceImpl extends ServiceImpl<ResultPapersMapper, ResultPapers> implements IResultPapersService
{
    @Autowired
    private ResultPapersMapper resultPapersMapper;

    @Autowired
    private SysUserPostMapper sysUserPostMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private AchievementTrashMapper achievementTrashMapper;

    /**
     * 查询论文
     *
     * @param id 论文主键
     * @return 论文
     */
    @Override
    public ResultPapers selectResultPapersById(Long id)
    {
        return resultPapersMapper.selectResultPapersById(id);
    }

    /**
     * 批量获取论文详细信息
     */
    @Override
    public List<ResultPapersVO> selectResultPapersByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return Collections.emptyList();
        }
        List<ResultPapers> resultPapersList = resultPapersMapper.selectResultPapersByIds(ids);
        List<ResultPapersVO> resultPapersVOList = new ArrayList<>();

        for (ResultPapers resultPaper : resultPapersList) {
            ResultPapersVO resultPapersVO = new ResultPapersVO();
            // 假设 ResultPapers 和 ResultPapersVO 有相同的字段，先进行复制
            BeanUtils.copyProperties(resultPaper, resultPapersVO);

            // 根据 userId 查询 nick_name
            SysUser sysUser = sysUserMapper.selectUserById(resultPaper.getUserId());
            resultPapersVO.setNickName(sysUser.getNickName());

            resultPapersVOList.add(resultPapersVO);
        }
        return resultPapersVOList;
    }

    /**
     * 查询论文列表
     *
     * @param resultPapers 论文
     * @return 论文
     */
    /**
     * 查询论文列表
     *
     * @param resultPapers 论文
     * @return 论文
     */
    @Override
    public TableDataInfo selectResultPapersList(ResultPapersDTO resultPapers) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long deptId = loginUser.getUser().getDeptId();

        // 若依默认超级管理员用户ID为1
        boolean isSuperAdmin = loginUser.getUser().getUserId().equals(1L);

        // 非超级管理员才进行部门过滤
        if (!isSuperAdmin) {
            resultPapers.setDeptId(deptId);
        }

        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotNull(pageDomain.getPageNum()) && StringUtils.isNotNull(pageDomain.getPageSize())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize(), orderBy)
                    .setReasonable(pageDomain.getReasonable());
        }

        List<ResultPapers> resultPapersList = resultPapersMapper.selectResultPapersListByDept(resultPapers);

        List<ResultPapersVO> resultPapersVOList = resultPapersList.stream().map(r -> {
            ResultPapersVO vo = new ResultPapersVO();
            BeanUtils.copyProperties(r, vo);
            SysUser sysUser = sysUserMapper.selectUserById(r.getUserId());
            vo.setNickName(sysUser.getNickName());
            return vo;
        }).collect(Collectors.toList());

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(resultPapersList).getTotal());
        rspData.setRows(resultPapersVOList);
        return rspData;
    }



    /**
     * 新增论文
     *
     * @param resultPapers 论文
     * @return 结果
     */
    @Override
    public int insertResultPapers(ResultPapers resultPapers)
    {
        return resultPapersMapper.insertResultPapers(resultPapers);
    }

    /**
     * 修改论文
     *
     * @param resultPapers 论文
     * @return 结果
     */
    @Override
    public int updateResultPapers(ResultPapers resultPapers)
    {
        return resultPapersMapper.updateResultPapers(resultPapers);
    }

    /**
     * 批量删除论文
     *
     * @param ids 需要删除的论文主键
     * @return 结果
     */
    @Override
    public int deleteResultPapersByIds(Long[] ids)
    {
        List<ResultPapers> resultPapersList = resultPapersMapper.selectResultPapersByIds(ids);
        for (ResultPapers resultPapers : resultPapersList) {
            AchievementTrash achievementTrash = new AchievementTrash();
            achievementTrash.setUserid(resultPapers.getUserId());
            achievementTrash.setAchievementType("论文");
            achievementTrash.setTitle(resultPapers.getTitle());
            achievementTrash.setAchievementId(resultPapers.getId());
            achievementTrash.setDeletedAt(new Date());
            achievementTrashMapper.insertAchievementTrash(achievementTrash);
        }
        return resultPapersMapper.deleteResultPapersByIds(ids);
    }

    /**
     * 删除论文信息
     *
     * @param id 论文主键
     * @return 结果
     */
    @Override
    public int deleteResultPapersById(Long id)
    {
        return resultPapersMapper.deleteResultPapersById(id);
    }

    /**
     * 根据论文id删除论文
     * @param id
     * @return
     */
    @Override
    public Result removePapersById(Integer id) {
        ResultPapers papers = getById(id);
        if (papers == null) {
            return Result.error("论文未找到");
        }

        String pdfPath = papers.getPdfPath();

        // 检查 pdfPath 是否为空
        if (pdfPath != null && !pdfPath.isEmpty()) {
//            try {
//                uploadController.deleteFile(pdfPath);
//            } catch (Exception e) {
//                return Result.error("删除文件失败");
//            }
        } else {
            log.warn("pdfPath 为空，无需删除文件");
        }

        boolean removed = removeById(id);
        if (!removed) {
            return Result.error("删除论文失败");
        }

        return Result.success("论文删除成功");
    }




}

